package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Region;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.query.QueryObject;
import cn.wolfcode.luowowo.repository.RegionRepository;
import cn.wolfcode.luowowo.service.IRegionService;
import cn.wolfcode.luowowo.util.AssertUtil;
import cn.wolfcode.luowowo.util.DBHelper;
import com.sun.corba.se.impl.oa.toa.TOA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Optional;

@Service
//@Transactional //事务最后处理
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepository repository;

    @Autowired
    private MongoTemplate template;


    @Override
    public Region get(String id) {
        Optional<Region> optional = repository.findById(id);
        if (optional != null) {
            return optional.get();
        }
        return null;
    }

    @Override
    public Page<Region> query(QueryObject qo) {
        //List<Region> list = repository.findAll(); //使用repostory对象查询的结果不满足带条件查询
        //使用MongoTemplate，可以满足条件查询，但是返回的是list集合，如何封装成Page对象？
        Query query = new Query();
        //PageImpl构造器的参数3：total
        long total = template.count(query, Region.class);

        if (total == 0) {
            //总条数为0 就返回空的page回去
            return Page.empty();
        }
        //PageImpl构造器的参数2：pageable
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, "_id");
        query.with(pageable);
        //PageImpl构造器的参数1：list
        List<Region> list = template.find(query, Region.class);

        return new PageImpl<Region>(list, pageable, total);
    }

    @Override
    public void update(Region region) {
        //使用save方法是全量更新，如果更新部分，会出现未更新的字段被null覆盖
        //repository.save(region);
        //方案一：查询————替代————保存（效率低，用update）
        //方案二：显示使用update逻辑 update set...

        //条件对象
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(region.getId()));
/*

        //更新的列
        Update update = new Update();
        update.set("name", region.getName());
        update.set("sn", region.getSn());
        update.set("refIds", region.getRefIds());
        update.set("ishot", region.getIshot());
        update.set("sequence", region.getSequence());
        update.set("info", region.getInfo());

        template.updateMulti(query, update, Region.class);
*/
        //使用工具简化更新的代码
        DBHelper.update(template, query, region, "name", "sn", "refIds", "ishot", "sequence", "info");

    }

    @Override
    public void save(Region region) {
       /* AssertUtil.hasLenth(region.getInfo(), "简介必填");
        AssertUtil.hasLenth(region.getName(), "名字必填");
        AssertUtil.hasLenth(region.getSn(), "编码必填");
        AssertUtil.isZero(region.getSequence(), "序号必填");
        AssertUtil.isZero(region.getSequence(), "序号必填");*/
       region.setId(null);
       repository.save(region);
    }

    @Override
    public void changeHotValue(String id, int hot) {
        //修改对象的hot状态值：先查在改效率低
        //直接update
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));

        Update update = new Update();
        update.set("ishot", hot);
        //更新
        template.updateMulti(query, update, Region.class);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    //查询热门区域
    @Override
    public List<Region> queryHotRegion() {
        return repository.findByIshotOrderBySequenceAsc(Region.STATE_HOT);

    }


}
